<?php


namespace app\api\service;


use app\admin\model\User;
use app\common\library\Sms as Smslib;
use app\common\model\Business;
use app\admin\model\Play;
use app\common\model\Order;
use app\common\model\OrderCancel;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use think\Config;
use think\Db;
use think\Exception;

class OrderService extends BaseService
{
    public function getOrderList($where = [], $page = 1, $pageSize = 20, $order = "place_time desc", $extend = [])
    {
        $orderObj = new Order();
        $start = ($page - 1) * $pageSize;
        $list = $orderObj->with(['shop', 'goods', 'proof'])
            ->where($where)
            ->order($order)
            ->limit($start, $pageSize)
            ->select();
        $count = $orderObj->with(['shop'])
            ->where($where)
            ->count();
        $mtWmConfig = Config::get('wm_config.mtwm');
        $elmWmConfig = Config::get('wm_config.elm');
        $style = '.web-app-text{color:#fff;display:flex;justify-content: center;align-items: center;font-size:13px;width:80px;height:30px;line-height:30px;}';
        foreach ($list as $k => $v) {
            $list[$k]['html_place_order'] = '';
            if (isset($v['shop']['wm_shop_id']) && $v['shop']['wm_shop_id'] != '') {
                $wmConfig = $v->wm_type == '2' ? $mtWmConfig : $elmWmConfig;
                $list[$k]['html_place_order'] = getWebappHtml($wmConfig['ysid'], $wmConfig['appid'], $wmConfig['path']['shop'], '<view class="web-app-text">去下单</view>', $style, ['wm_shop_id' => $v['shop']['wm_shop_id']]);
//                $list[$k]['html_place_order'] = '<wx-open-launch-weapp id="launch-btn" username="gh_6506303a12bb" path="taoke/pages/shopping-guide/index?scene=QezpCXu" @launch="handleLaunchFn" @error="handleErrorFn"><template><style>.web-app-img{width: 40px;height:40px;}</style><image class="web-app-img" mode="aspectFill" src="https://xcm.trnall.cn/imgs/icons/new_home_elem_icon.png"></image></template></wx-open-launch-weapp>';
            }
        }
        $lastPage = $count / $pageSize >= (int)$count / $pageSize ? (int)($count / $pageSize) + 1 : (int)($count / $pageSize);
        $data = ['last_page' => $lastPage, 'list' => $list, 'total' => $count, 'goods' => null];
        if (isset($where['goods_id']) && $where['goods_id'] > 0) {
            $data['goods'] = (new Goods())->where('id', $where['goods_id'])->find();
        }
        return $data;
    }

    public function createOrder($userId, $play, $play_order_no, $user_id, $nickname,$roll,$roll2,$address)
    {
        $shop_platform = Db::name('shop_platform')->where('shop_no',$play['play_no'])->find();
        Db::startTrans();
        try {
            $orderData = [
                'play_order_no' => $play_order_no,
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'play_no' => $play['play_no'],
                'shop_name' => $play['shop_name'],
                'platform_no' => isset($shop_platform['platform_no'])?$shop_platform['platform_no']:'',
                'rebate_amt' => $play['shop_settlement'], // 商户要支付的返点金额
                'service_charge_amt' => $play['service_amt'], // 平台手续费金额
                'actual_rebate_amt' => $play['back_money'], // 实际用户得到的返点金额
                'user_pay' => $play['user_pay'], // 满多少
                'place_time' => time(),
                'expire_time' => time() + intval(config('sn_expire')),  // 上传单号的过期时间
                'create_by' => $user_id,
                'location' => $address,
            ];
            if ($play['pay_status']==2) {
                $orderData['is_pay'] = 1;
            }
            $order = (new \app\common\model\Order());
            $order->data($orderData)->allowField(true)->save();
            $order['proof'] = [];
            $play = (new \app\admin\model\Play())->lock(true)->where('id', $play['id'])->find();
            //减少剩余名额
            $play->stock = $play->stock - 1;
            $play->save();
            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $play_order_no,
                'create_by' => $nickname,
                'create_by_id' => $user_id,
                'is_front' => 1,
                'info' => '报名',
            ]);
            // 消耗优惠券
            $res = \app\common\model\UserRollLog::useRoll($roll,$play['play_no']);
            if (!$res) {
                Db::rollback();
                return false;
            }
            // 超前抢单
            if ($roll2) {
                $res = \app\common\model\UserRollLog::useRoll($roll2,$play['play_no']);
                if (!$res) {
                    Db::rollback();
                    return false;
                }
            }
            Db::commit();
            return $order;
        } catch (Exception $exception) {
            Db::rollback();
            \think\Log::write('活动报名exception=>'.$exception->getMessage());
            return false;
        }
    }

    public function getOrderDetail($id, $where = [])
    {
        $orderObj = new Order();
        $where['id'] = $id;
        $order = $orderObj->with(['shop'])
            ->where($where)
            ->find();
        if ($order) {
            $order['proof'] = null;
            $order['play'] = null;
            if ($order['is_yunzhan']>0) {
                $proof = Db::name('play_order_proof')->where('play_order_no',$order['yunzhan_order_no'])->order('id desc')->field('wm_order_sn,one_image,two_image,three_image,platform_no,supplement,machine_audit_state,actual_pay')->find();
                if ($proof) {
                    $proof['one_image_url'] = config('upload_domain').$proof['one_image'];
                    $proof['two_image_url'] = config('upload_domain').$proof['two_image'];
                    $proof['three_image_url'] = config('upload_domain').$proof['three_image'];
                    $proof['supplement'] = json_decode($proof['supplement'],1);
                    if (isset($proof['supplement']['one_image'])) {
                        $proof['supplement']['one_image_url'] = config('upload_domain').$proof['supplement']['one_image'];
                    }
                    if (isset($proof['supplement']['two_image'])) {
                        $proof['supplement']['two_image_url'] = config('upload_domain').$proof['supplement']['two_image'];
                    }
                    if (isset($proof['supplement']['three_image'])) {
                        $proof['supplement']['three_image_url'] = config('upload_domain').$proof['supplement']['three_image'];
                    }
                    $order['proof'] = $proof;
                }
            } else {
                $proof = Db::name('play_order_proof')->where('play_order_no',$order['play_order_no'])->order('id desc')->field('wm_order_sn,one_image,two_image,three_image,platform_no,supplement,machine_audit_state,actual_pay')->find();
                if ($proof) {
                    $proof['one_image_url'] = config('upload_domain').$proof['one_image'];
                    $proof['two_image_url'] = config('upload_domain').$proof['two_image'];
                    $proof['three_image_url'] = config('upload_domain').$proof['three_image'];
                    $proof['supplement'] = json_decode($proof['supplement'],1);
                    if (isset($proof['supplement']['one_image'])) {
                        $proof['supplement']['one_image_url'] = config('upload_domain').$proof['supplement']['one_image'];
                    }
                    if (isset($proof['supplement']['two_image'])) {
                        $proof['supplement']['two_image_url'] = config('upload_domain').$proof['supplement']['two_image'];
                    }
                    if (isset($proof['supplement']['three_image'])) {
                        $proof['supplement']['three_image_url'] = config('upload_domain').$proof['supplement']['three_image'];
                    }
                    $order['proof'] = $proof;
                }
                // 爆单宝订单
                if ($order['is_bdb']==1) {
                    $order['play'] = json_decode($order['proposal'],1);
                    $order['shop'] = ['shop_name'=>$order['play']['shop_name'],'qrcode_pic'=>$order['play']['qrcode_pic'],'platform_no'=>$order['play']['platform_no'],'is_xls'=>$order['play']['is_xls'],'elm_appenter'=>$order['play']['elm_appenter'],'lat'=>$order['play']['lat'],'lng'=>$order['play']['lng'],'address'=>$order['play']['address'],'shop_type_text'=>$order['play']['shop_type'],'shop_type'=>$order['play']['shop_type'],'logo_pic_url'=>$order['play']['logo_pic_url']];
                    // if (isset($order['play']['dpzxelm'])) $order['shop']['dpzxelm'] = $order['play']['dpzxelm'];
                } else {
                    $order['play'] = Play::where('play_no',$order['play_no'])->find();
                    if (isset($order['play']['play_label_text']) && $order['play']['play_label_text']=='正常活动') $order['play']['play_label_text']='正常活动';
                    $order['play']['back_money'] = floatval($order['play']['back_money']);
                    $order['play']['user_pay'] = floatval($order['play']['user_pay']);
                    $order['play']['play_type'] = Play::getPlayTypeAttr($order['play']['play_type'],$order['play']);
                }
            }
        }
        if ($order) return $order;
        return null;
    }

    public function proof($order, $proof, $data = [], $user_id, $nickname, $is_dissatisfied)
    {
        Db::startTrans();
        try {
            $info = '提交凭据';
            $proof->isUpdate(true)->save($data);
            $order->order_status = 2;
            // 如果是不满意提交
            if ($is_dissatisfied) {
                $order->order_status = -5;
                $info = '不满意提交';
            }
            $order->save();

            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $order['play_order_no'],
                'create_by' => $nickname,
                'create_by_id' => $user_id,
                'is_front' => 1,
                'info' => $info,
            ]);
            Db::commit();
            return ['code' => 200, 'msg' => '成功'];
        } catch (Exception $exception) {
            Db::rollback();
            return ['code' => 400, 'msg' => $exception->getMessage()];
            \think\Log::write('提交活动凭据exception=>'.$exception->getMessage());
        }
    }

    /**
     * @param $order
     * @param int $cancelType '1': '用户取消', '2': '超时取消', '3': '商家取消', '4': '管理员取消'
     * @param array $extend
     * @return bool
     */
    public function cancel($order, $user_id, $cancelType = 1, $extend = [])
    {
        Db::startTrans();
        // try {
            // 如果用户在商家复审时取消订单，对用户进行限制
            if ($order->order_status==6 && order_count_read($user_id)<5) {
                // 审核通过
                $result = Db::name('user')->where('id',$user_id)->update([
                    'is_limited' => 1,
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$user_id,
                    'status'=>1,
                    'submit_by'=>$user_id,
                    'mode'=>2
                ]);
            }
            $orderCancelObj = new OrderCancel();
            $statusList = $orderCancelObj->getStatusList();
            $order_status = $order->order_status;
            $order->order_status = $cancelType == 1 ? -1 : -2;
            $order->update_by = $user_id;
            $order->save();
            $play_order_no = $order['play_order_no'];
            if (isset($extend['source']) && $extend['source']) {
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],json_decode($order['proposal'],1));
                $play['user_id'] = $shop['have_uid'];
                $bwc = new \services\BwcService();
                $res = $bwc->unApply($order['yunzhan_order_no'],$extend['mobile']);
                \think\Log::write('取消报名：'.$res);
                // $res = '{"status":true,"code":200,"message":"success","data":true}';
                $decode = json_decode($res,1);
                if ($decode['message']!='success') {
                    return false;
                }
                $play_order_no = $order['yunzhan_order_no'];
            } else {
                if ($order['is_bdb']==0) {
                    //库存回归
                    $play = (new Play())->lock(true)->where(['play_no' => $order->play_no])->find();
                    $play->stock = $play->stock + 1;
                    $play->isUpdate(true)->save();
                    // 改变活动状态
                    $complete_order = Db::name('play_order')->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                    if (($complete_order==$play['num'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['num']-$play['stock'] && $play['num']-$play['stock']>0)) {
                        // 如果是前台发布的活动，此时直接完成活动,否则状态改为待支付
                        if ($play['pay_status']==3 && $play['is_pay']==1) {
                            $play->play_status = 5;
                            $play->pay_status = 2;
                            $play->update_by = 'crontab';
                            $play->save();
                            // 冻结金额减少
                            $money = -1*$play['shop_settlement'];
                            (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $order['play_order_no'], 1);
                            // 商家余额增加
                            $money = -1*$money;
                            (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $order['play_order_no']);
                            // 订单支付状态
                            // Db::name('play_order')->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,-9]]])->update(['is_pay'=>1,'pay_time'=>time()]);
                        } else {
                            $play->play_status = 3;
                            $play->acture_total_money = (float)Db::name('play_order')->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                            $play->save();
                        }
                    }
                } else {
                    $play = json_decode($order['proposal'],1);
                    if ($order_status==6) {
                        $bdblocal = 'http://127.0.0.1:8715';
                        $url = $bdblocal.'/api/order/cancel';
                        $param = ['play_order_no' => $order['play_order_no']];
                        $params = json_encode($param);
                        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
                        $res = \fast\Http::post($url,$params,[],$header);
                        $decode = json_decode($res,1);
                        if ($decode['code']==0) return false;
                    }
                }
            }

            $data = [
                'merchant_id' => $play['user_id'],
                'shop_no' => $order['shop_no'],
                'user_id' => $order['user_id'],
                'play_order_no' => $play_order_no,
                'deal_status' => $cancelType,
                'handle_time' => time(),
                'handle_desc' => $statusList[$cancelType]
            ];
            $orderCancelObj->data($data)->save();

            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $play_order_no,
                'create_by' => isset($extend['nickname'])?$extend['nickname']:'',
                'create_by_id' => $user_id,
                'is_front' => 1,
                'info' => '取消订单',
            ]);
            // 返还使用的优惠券
            $user_roll_log = Db::name('user_roll_log')->where(['play_no'=>$order['play_no']])->field('roll_id')->select();
            if ($user_roll_log) {
                foreach ($user_roll_log as $key => $value) {
                    Db::name('user_roll')->where('id',$value['roll_id'])->update(['status'=>1,'update_dt'=>date('Y-m-d H:i:s')]);
                }
            }
            Db::commit();
            return true;
        // } catch (Exception $e) {
        //     Db::rollback();
        //     \think\Log::write('取消活动exception=>'.$e->getMessage());
        //     return false;
        // }
    }

    public function handleOrder()
    {
        $wmConfig = Config::get('wm_config');
        $orderObj = new Order();
        $businessOjb = new Business();
        $maxUpload = $wmConfig['max_upload'] ?? 3 * 3600;
        //提前30分钟通知
        $list = $orderObj
            ->where([
                'status' => ['=', 1],
                'place_time' => ['between', [time() - $maxUpload, time() - $maxUpload + 1800]],
                'exp_message' => ['=', 0]
            ])
            ->select();
        $text = '通知订单数:' . count($list) . "个\r\n";
        p($list, 'handleOrder-1' . $text);

        if (!empty($list)) {
            Db::startTrans();
            try {
                $orderIds = [];
                $userIds = [];
//            通知用户并标记
                foreach ($list as $k => $v) {
                    $orderIds[] = $v['id'];
                    if (!in_array($v['user_id'], $userIds)) $userIds[] = $v['user_id'];
                }
                if (!empty($userIds)) {
                    $mobileArr = (new User())->where(['id' => ['in', $userIds]])->column('mobile');
                    $mobileArr = array_filter($mobileArr);
                    if (!empty($mobileArr)) {
                        $mobile = implode(',', $mobileArr);
                        $text = '通知手机号:' . $mobile . "\r\n";
                        $res = true;
                        $res = Smslib::notice($mobile, '您好，您在小餐谋这边的外卖活动订单时间快要超时啦，请快去平台提交订单截图，如有疑问请联系客服。', 'SMS_243261409');
                        if ($res) {
                            //标记已发送
                            (new Order())->isUpdate(true)->save(['exp_message' => '1'], ['id' => ['in', $orderIds]]);
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $text .= "订单通知出现异常:" . $e->getMessage() . "\r\n";
            }
        }
        //取消已超时订单
        $list = $orderObj
            ->where([
                'status' => ['=', 1],
                'place_time' => ['<', time() - $maxUpload]
            ])
            ->field('id,status,place_time,business_id,shop_id,user_id,goods_id,normal_rich_desc')
            ->select();
        p([count($list), $list], 'handleOrder-2');
        $text .= '已超时订单数:' . count($list) . "个\r\n";
        if (!empty($list)) {
            //取消订单并根据情况返还库存
            Db::startTrans();
            try {
                //取消订单
                $res1 = $orderObj
                    ->where([
                        'status' => ['=', 1],
                        'place_time' => ['<', time() - $maxUpload]
                    ])
                    ->update(['status' => '-2']);
                $text .= "超时订单处理结束\r\n";
                p($res1, 'res1');
                //记录本次取消
                $orderCancelOjb = new OrderCancel();
                $statusList = $orderCancelOjb->getStatusList();
                $allData = [];
                $goodsData = [];
                foreach ($list as $k => $order) {
                    $data = [
                        'business_id' => $order['business_id'],
                        'shop_id' => $order['shop_id'],
                        'user_id' => $order['user_id'],
                        'order_id' => $order['id'],
                        'status' => 2,
                        'handle_time' => time(),
                        'handle_desc' => $statusList[2]
                    ];
                    if (isset($goodsData[$order['goods_id']])) $goodsData[$order['goods_id']] += 1;
                    else $goodsData[$order['goods_id']] = 1;
                    $allData[] = $data;
                }
                $text .= "超时订单处理已记录\r\n";
                p($goodsData, '$goodsData');
                if (!empty($allData)) $orderCancelOjb->saveAll($allData);
                $goodsObj = new Goods();
                $goodsIds = array_keys($goodsData);
                if (!empty($goodsIds)) {
                    //如果是未结算未结束的活动，回归库存
                    $goodsList = $goodsObj->where([
                        'is_settle' => ['=', 0],
                        'is_show' => ['=', 1],
                        'status' => ['=', 1],
                        'start_time' => ['<', time()],
                        'end_time' => ['>', time()],
                        'id' => ['in', $goodsIds]
                    ])
                        ->select();
                    if (!empty($goodsList)) {
                        $updateData = [];
                        foreach ($goodsList as $k => $v) {
                            if (isset($goodsData[$v['id']]) && $goodsData[$v['id']] > 0) {
                                $updateData[] = [
                                    'id' => $v['id'],
                                    'stock' => $v['stock'] + $goodsData[$v['id']]
                                ];
                            }
                        }
                        p($updateData, 'handleOrder-3');
                        $text .= "超时订单库存返还数:" . count($updateData) . "个商品\r\n";
                        if (!empty($updateData)) $goodsObj->isUpdate(true)->saveAll($updateData);
                    }
                    //如果是已结算已支付的活动，解冻资金
                    $goodsList = $goodsObj->where([
                        'is_settle' => ['=', 1],
                        'is_show' => ['=', 1],
                        'is_pay' => ['=', 1],
                        'id' => ['in', $goodsIds]
                    ])
                        ->select();
                    if (!empty($goodsList)) {
                        $ids = [];
                        foreach ($goodsList as $k => $v) {
                            $ids[$v['id']] = [
                                'id' => $v['id'],
                                'business_id' => $v['business_id'],
                                'process_money' => $v['process_money'],
                                'normal_rich_desc' => $v['normal_rich_desc'],
                            ];
                        }
                        $moneyData = [];
                        foreach ($list as $k => $v) {
                            if (isset($ids[$v['goods_id']]) && !empty($ids[$v['goods_id']])) {
                                $tempMoney = bcadd($ids[$v['goods_id']]['process_money'], $v['normal_rich_desc'],2);
                                if (isset($moneyData[$v['business_id']])) {
                                    $moneyData[$v['business_id']] = bcadd($moneyData[$v['business_id']], $tempMoney,2);
                                } else {
                                    $moneyData[$v['business_id']] = $tempMoney;
                                }
                            }
                        }
                        p([$moneyData, $ids], 'moneyData');
                        if (!empty($moneyData)) {
                            foreach ($moneyData as $k => $v) {
                                $business = $businessOjb->get($k);
                                if ($business) {
                                    $business->wallet = bcadd($business->wallet, $v,2);
                                    $business->freeze_wallet = bcsub($business->freeze_wallet, $v);
                                    $business->save();
                                    $text .= "商家{$business->nickname}解冻资金:{$v}\r\n";
                                }
                            }
                        }
                    }
                }
                p($goodsData, 'handleOrder-4');
                $text .= "订单处理结束\r\n";
                Db::commit();
                return ['code' => 1, 'msg' => $text];
            } catch (Exception $e) {
                $text .= "订单处理出现异常:" . $e->getMessage() . "\r\n";
                p($e->getMessage(), 'handleOrder-catch');
                Db::rollback();
                return ['code' => 0, 'msg' => $text];
            }
        }
        return ['code' => 1, 'msg' => $text];
    }

    // 生成第一第二张图
    public function buildImg($param,$order_type)
    {
        // 新建图象
        if ($order_type==1) {
            $pic=getImageCreate(ROOT_PATH.'/public/assets/img/meituan_bg.png');
        } else {
            $pic=getImageCreate(ROOT_PATH.'/public/assets/img/elem_bg.png');
        }
        foreach ($param as $key => $value) {
            // imagecolorallocate第一次调用就是背景色，这里为了演示就是黑色
            $black=imagecolorallocate($pic,0,0,0);
            // 定义字体
            $font=ROOT_PATH.'/public/assets/fonts/msyh.ttf';
            // 定义输出字体串
            $text = $value[0];
            // if ($key<3) {
                $text = mb_convert_encoding($text, "UTF-8");
                $text = to_entities($text);
            // } else {
            //     $text = mb_convert_encoding($text, "utf-8", "gb2312");///解决乱码问题
            // }
            // 打印TTF文字到图中
            imagettftext($pic,10,0,$value[1],$value[2],$black,$font,$text);
        }
        $dir = '/uploads/share/';    //生成的图片目录
        //图片路径
        $path = $dir . date("Ymd", time()) . '/';
        if (!file_exists('.' . $path))
            mkdir('.' . $path, 0775, true);
        $imagePath = $path . 'code'.time() . mt_rand(1000, 9999) . '.jpg';
        //生成图片
        Imagejpeg($pic, '.' . $imagePath);
        $ossService = new \services\OssService();
        $apppath = ROOT_PATH.'/public'.$imagePath;
        $upload_file = file_get_contents($apppath);
        $savekey = trim($imagePath,'/');
        $file=$ossService->upload_file_content($upload_file,$savekey);
        if (!$file) {
            // 上传失败获取错误信息
            return false;
        }
        chmod($apppath,0755);
        unlink($apppath);
        $url = '/'.$savekey;
        return $url;
    }


    public function completeOrder($order,$proof,$play,$user_id,$nickname,$amounts,$pay_time,$order_id)
    {
        Db::startTrans();
        try {
            $data = [];
            // 提交渠道：1-H5，2-在线识别3-APP人工通道
            $data['platform'] = 0;
            if ($_SERVER['HTTP_PLATFORM']=='wxOfficialAccount') {
                $data['platform'] = 1;
                $order->platform = 1;
            } elseif ($_SERVER['HTTP_PLATFORM']=='wxMiniProgram') {
                $data['platform'] = 4;
                $order->platform = 4;
            } elseif ($_SERVER['HTTP_PLATFORM']=='App') {
                if (in_array($proof['machine_audit_state'], [2,3])) {
                    $data['platform'] = 2;
                    $order->platform = 2;
                } else {
                    $data['platform'] = 3;
                    $order->platform = 3;
                }
            }
            $User = new \app\common\model\User();
            $user = $User->get($order['user_id']);
            // 如果匹配到cps,生成第一第二张图
            $mb_strlen = mb_strlen($play['shop_name']);
            if ($mb_strlen>14) {
                $shop_name = mb_substr($play['shop_name'],0,14).'...';
                $x = 175;
            } else {
                $shop_name = $play['shop_name'];
                $x = (14-$mb_strlen)*10+175+10;
            }
            $arr = [
                [$shop_name,$x,443],
                [$order_id,205,475],
                [date('Y-m-d H:i:s',$pay_time),226,507],
                [$amounts,320,539],
            ];
            $data['actual_pay'] = isset($amounts)&&$amounts?$amounts:0;
            $resimg = $this->buildImg($arr,$play['shop_type']);
            if ($resimg) {
                $data['one_image'] = $resimg;
                $data['two_image'] = $data['one_image'];
            }
            // 如果有图片的话不要覆盖空数据
            if (!$data['one_image']) {
                $data['one_image'] = $proof['one_image'];
            }
            if (!$data['two_image']) {
                $data['two_image'] = $proof['two_image'];
            }
            // 商家复审的情况
            $shop = Db::name('shop')->where(['shop_no'=>$order['shop_no']])->field('is_sjzp,middleman_id,shop_no,shop_type')->find();
            // 用户获得吃豆
            $beans = $order['actual_rebate_amt'];
            $User->beans($beans,$order['user_id'],'下单返豆',$order['play_order_no']);
            // 实际返豆
            $order->actual_rebate_amt = $beans;
            // 订单状态
            $order->order_status = 3;
            $order->update_by = $user_id;
            $order->save();
            //
            $data['handle_status'] = 1;
            $data['handle_time'] = time();
            $data['upload_time'] = time();
            $proof->isUpdate(true)->save($data);
            // $this->orderLog($order->id,$order->play_order_no,'机审通过',$nickname,$user_id);
            OrderLog::create([
                'play_order_id' => $order->id,
                'play_order_no' => $order->play_order_no,
                'info' => '机审通过',
                'create_by' => $nickname,
                'create_by_id' => $user_id,
                'is_front' => 1,
            ]);
            // 消息处理
            // $user = $User->get($order['user_id']);
            // 前台发布活动，当前这一单冻结金额减少
            if ($play['is_pay']==1 && $play['pay_status']==3) {
                // 当前这一单冻结金额减少
                $money = -1*($order['actual_rebate_amt']+$order['service_charge_amt']);
                (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $order['play_order_no'], 1);
                $order->is_pay = 1;
                $order->pay_time = time();
                $order->save();
            }
            // 发送微信消息
            $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
            if ($qywx) {
                $external_userid = $qywx['ExternalUserID'];
                $sender = $qywx['UserID'];
                $title = '您的活动订单审核成功';
                $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                $url = config('h5_domain').'/#/pages/index/order';
                $lPublics = new \app\api\service\UserService();
                $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
            }
            // 发送app消息
            // if (isset($user['birthday']) && $user['birthday']) {
                $lPublics = new \app\api\service\UserService();
                $title = '您的活动订单审核成功';
                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                $url = '/pages/index/order';
                $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$order->play_order_no);
                $title = '【完成一笔订单】任务达成';
                $desc = '获得2次抽奖机会（当日有效）';
                $url = '/index/raffle/raffle';
                $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
            // }
            if ($order['is_yunzhan']==0 && $order['is_bdb']==0) {
                $complete_order = (new Order())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                // 状态改为待支付
                if (($complete_order==$play['num'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['num']-$play['stock'] && $play['num']-$play['stock']>0)) {
                    // 如果是前台发布的活动，此时直接完成活动,否则状态改为待支付
                    if ($play['pay_status']==3 && $play['is_pay']==1) {
                        $play->play_status = 5;
                        $play->pay_status = 2;
                        $play->last_pay_time = time();
                        $play->update_by = $nickname;
                        $play->acture_total_money = (float)(new Order())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                        $play->save();
                        // 冻结金额减少
                        $money = -1*($play['total_money']-$play['acture_total_money']);
                        (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no'], 1);
                        // 商家余额增加
                        $money = -1*$money;
                        (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no']);
                        // 订单支付状态
                        (new Order())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->update(['is_pay'=>1,'pay_time'=>time()]);
                    } else {
                        $play->play_status = 3;
                        $play->acture_total_money = (float)(new Order())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                        $play->save();
                    }
                }
            }
            // 分销和抽奖机会和积分
            if ($order->order_status==3) {
                // 中间人佣金
                if ($play['is_pay']==1) {
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                    if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                        (new \app\common\model\User())->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $order['play_order_no']);
                    }
                }
                OrderLog::create([
                    'play_order_id' => $order->id,
                    'play_order_no' => $order->play_order_no,
                    'info' => '订单完成',
                    'create_by' => $nickname,
                    'create_by_id' => $user_id,
                    'is_front' => 1,
                ]);
                if ($user['pid']) {
                    $order_num = order_count($order['user_id']);
                    if ($order_num==1) {
                        $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                        // 上级用户新增有效团员
                        \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $order['play_order_no'], '新增有效团员');
                        // 如果是第一单，则上级用户获得一个有效用户，加积分
                        $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                        if (!$res) {Db::rollback();return ['msg'=>'上级用户获取积分失败','code'=>0];}
                        // unipush
                        $user2 = $User->get($user['pid']);
                        // if (isset($user2['birthday']) && $user2['birthday']) {
                            $lPublics = new \app\api\service\UserService();
                            $title = '【新增一位有效团员】任务达成';
                            $desc = '获得1次抽奖机会（当日有效）';
                            $url = '/index/raffle/raffle';
                            $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                        // }
                    } elseif ($order_num==2) {
                        $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                    } else {
                        $rate = (int)\think\Config::get('site.third_order');
                        $amount = round($order['service_charge_amt']*$rate*0.01,2);
                        // 当前是不是会员团长
                        $user1 = \app\common\model\User::get($user['pid']);
                        if ($user1['hytz']==1) {
                            // 团长的有效用户数是否大于指定的用户数
                            $invitation_new_reward = \think\Config::get('site.yyty');
                            $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                            if (count($user_distribution)>$invitation_new_reward) {
                                $ratenim = (float)\think\Config::get('site.third_order_min3');
                            } else {
                                $ratenim = (float)\think\Config::get('site.third_order_min2');
                            }
                        } else {
                            $ratenim = (float)\think\Config::get('site.third_order_min');
                        }
                        if ($amount<$ratenim) $amount = $ratenim;
                    }
                    if ($amount) {
                        \app\common\model\UserDistribution::create([
                            'play_order_no' => $order['play_order_no'],
                            'uid' => $order['user_id'],
                            'pid' => $user['pid'],
                            'play_no' => $order['play_no'],
                            'amount' => $amount,
                            'order_times' => $order_num,
                        ]);
                        // 上级用户加吃豆
                        $res = $User->beans($amount, $user['pid'], '下级返利', $order['play_order_no']);
                        if (!$res) {Db::rollback();return ['msg'=>'上级返利失败','code'=>0];}
                        // 发送app消息
                        // $user = \app\common\model\User::get($user['pid']);
                        if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                        // if (isset($user['birthday']) && $user['birthday']) {
                            $lPublics = new \app\api\service\UserService();
                            $title = '团长奖励获得吃豆';
                            $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                            $url = '/pages/user/user-data';
                            $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                        // }
                    }
                }
                // 用户加积分
                $res = $User->score(config('order_score'),$order['user_id'],'下单获得');
                if (!$res) {Db::rollback();return ['msg'=>'增加积分失败','code'=>0];}
                // 完成订单
                \app\common\model\UserLuckdrawLog::addLog($order['user_id'], 1, $order['play_order_no'], '完成订单', 2);
            }
            // 云瞻活动上传凭证
            if ($order['is_yunzhan'] && in_array($order->order_status, [3,6])) {
                $bwc = new \services\BwcService();
                $screen_shots = '';
                if (isset($proof['one_image'])) $screen_shots.=config('upload_domain').$proof['one_image'].',';
                if (isset($proof['two_image'])) $screen_shots.=config('upload_domain').$proof['two_image'].',';
                if (isset($proof['three_image'])) $screen_shots.=config('upload_domain').$proof['three_image'].',';
                $e_commission = floatval($order['actual_rebate_amt']+$order['service_charge_amt']);
                $actual_pay = $proof['actual_pay']==0?$order['user_pay']:$proof['actual_pay'];
                $res = $bwc->uploadCredential($order['yunzhan_order_no'],$user['mobile'],trim($screen_shots,','),$actual_pay,$order['wm_order_sn'],$e_commission);
                // $res='{"status":true,"code":200,"message":"success","data":true}';
                \think\Log::write('提交凭证回调'.$res);
                $decode = json_decode($res,1);
                if ($decode['message']!='success') {
                    return ['msg'=>$decode['message'],'code'=>0];
                }
            }
            if ($order['is_bdb']==1 && in_array($order['order_status'], [3,6])) {
                (new \think\cache\driver\Redis())->lPush('bdborder',$order['play_order_no']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['msg'=>$e->getMessage(),'code'=>0];
        }
        return ['msg'=>'success','code'=>1];
    }



    public static function ip2address($ip)
    {
        $config = get_addon_config('address');
        $maptype = $config['maptype'];
        if (!isset($config[$maptype . 'key']) || !$config[$maptype . 'key']) {
            return false;
        }
        $res = file_get_contents("https://apis.map.qq.com/ws/location/v1/ip?ip=".$ip."&output=json&key=".$config[$maptype . 'key']);
        $decode = json_decode($res,1);
        if (isset($decode['status']) && $decode['status']==0) {
            return $res;
        }
        return false;
    }
}